<template>
  <div class="resume-edit">
    <UploadImage :data="picList" @change="(v) => (picList = v)" :count="+options.count" />
    <div class="button-wrap">
      <button
        loading-text="提交中..."
        class="button"
        :loading="loadingSubmitButton"
        @click="submit"
      >
        保存
      </button>
    </div>
  </div>
</template>

<script lang="ts">
import { ref, onMounted, reactive } from 'vue';
import Taro from '@tarojs/taro';
import { UploadImage } from '@/components';
import { getCurrentInstance } from '@tarojs/taro';
import { updateUserResume } from '@/service/resume.service';
import { useResumeStore } from '@/stores';
import './index.less';

type IOptions = {
  id: number;
  field: string;
  title: string;
  count: number;
};
export default {
  components: {
    UploadImage,
  },

  setup() {
    const loadingSubmitButton = ref(false);
    const picList = ref<String[]>([]);
    const resumeStore = useResumeStore();
    const options = reactive<IOptions>(getCurrentInstance().router?.params);

    onMounted(async () => {
      await resumeStore.getResume();
      if (resumeStore.data[options.field]) {
        picList.value = resumeStore.data[options.field].split(',');
      }
    });

    const submit = async () => {
      loadingSubmitButton.value = true;
      try {
        if (!picList.value) {
          throw new Error('请上传健康证及体检报告');
        }
        await updateUserResume({
          id: resumeStore.data.id,
          [options.field]: picList.value.join(','),
        });
        await Taro.showToast({
          title: '修改成功',
        });
        Taro.navigateBack();
      } catch (err) {
        Taro.showToast(err.message);
        loadingSubmitButton.value = false;
      }
    };

    return {
      submit,
      picList,
      options,
      loadingSubmitButton,
    };
  },
};
</script>
